package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-11-12
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断与用户名和密码不为空
        if (StringUtils.isBlank (loginDto.getName ()) || StringUtils.isBlank (loginDto.getPassword ())){
            return ResponseResult.errorResult (AppHttpCodeEnum.NAME_PSW_REQUIRE);
        }
        //1.根据用户名查询
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<> ();
        queryWrapper.eq (AdUser::getName,loginDto.getName ());
        AdUser one = this.getOne (queryWrapper);
        if (one==null){
            //如果查询不到，就返回一个错误提示
            return ResponseResult.errorResult (AppHttpCodeEnum.NAME_ERROR);
        }
        //2.如果能查到，再比较密码
        //页面传过来的密码和盐相加
        String passwoed_page = DigestUtils.md5Hex ( loginDto.getPassword ()+one.getSalt ());
        //数据库的密码
        String password_db = one.getPassword ();
        if (!StringUtils.equals (passwoed_page,password_db)){
            //密码不一致，就返回一个错误提示
            return ResponseResult.errorResult (AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码一致，就返回结果
        Map resultMap = new HashMap ();
        one.setSalt ("");
        one.setPassword ("");
        one.setPhone ("");
        one.setEmail ("");
        resultMap.put ("user",one);

        Map map = new HashMap();
        map.put("userId", one.getId ());
        map.put("name", one.getName ());
        String token = AppJwtUtil.getToken(map);
        resultMap.put ("token",token);

        return ResponseResult.okResult (resultMap);
    }
}
